package com.dudu.timer;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.dudu.bean.IfControlCheckConclusionPushBean;
import com.dudu.dao.InfoControlDao;
import com.dudu.utils.DateUtils;
import com.dudu.utils.EnumUtility;
import com.dudu.utils.HttpClientCenter;
import com.dudu.utils.HttpRequest;
import com.dudu.utils.ThreadPoolUtils;

import net.sf.json.JSONObject;

/**
 * 推送信控审核结果任务类
 * @author zx
 *
 */
public class PushInfoControlCheckConclusionJob implements Job {

	private static final Logger log = core.util.Logger
			.getLogger(PushInfoControlCheckConclusionJob.class.getSimpleName());

	private static InfoControlDao dataOperator = new InfoControlDao();

	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		List<JSONObject> list = null;
		boolean hasJob = false;
		/**
		 * 进行同步控制，获取数据后立刻更新状态
		 * 避免多线程重复获取相同数据
		 */
		synchronized (PushInfoControlCheckConclusionJob.class) {
			list = dataOperator.queryInfoControlPushInfo();
			StringBuilder ids = new StringBuilder();
			if (list != null && !list.isEmpty()) {
				hasJob = true;
				for (int i = 0; i < list.size(); i++) {
					JSONObject data = list.get(i);
					if (i > 0)
						ids.append(",");
					ids.append(data.getInt("id"));
				}
				// 更新状态
				dataOperator.updateInfoControlPushInfoStatus("3", ids.toString());
			}
		}
		if (hasJob)
			ThreadPoolUtils.getThreadPoolUtils().getExecutorService()
					.execute(new PushInfoControlCheckConclusionThread(list));

	}
    
	/**
	 * 内部类，推送信控审核结果线程
	 * @author zx
	 *
	 */
	private static class PushInfoControlCheckConclusionThread implements Runnable {
		
		private static final String INVALID_URL="invalid_url";
		
		private static final String SUCCESS_CODE="0000";//推送成功状态码

		private List<JSONObject> data;

		public PushInfoControlCheckConclusionThread(List<JSONObject> data) {
			this.data = data;
		}

		@Override
		public void run() {
            for (int i = 0; i < data.size(); i++) {
            	try{
                	JSONObject pushInfo=data.get(i);
                	String url=pushInfo.getString("push_url");
                	int count=pushInfo.getInt("push_count");
                	int id=pushInfo.getInt("id");
                	pushInfo.remove("id");
                	pushInfo.remove("push_url");
                	pushInfo.remove("push_count");
                	String response="";
            		JSONObject object = new JSONObject();
            		object.put("data", pushInfo);
            		object.put("describe", "请按照文档接口回复");
            		String status="1";
            		String message="";
            		if(EnumUtility.isNotBlank(url)){//推送地址不能为空
            			response=pushCheckInfo(url,object.toString());
            			log.info("response..."+response);
            			if(EnumUtility.isNotBlank(response)){
            				if(response.equals(INVALID_URL)){
                				status="2";
                				message="第三方推送地址格式错误";
            				}else{
                				JSONObject retJson = JSONObject.fromObject(response);
                				message = retJson.optString("desc");
            					String code = retJson.optString("code");      				
                				if(!SUCCESS_CODE.equals(code)){//只要code不为0000，就视为失败
                					status="2";
                				}
            				}
            			}else{
            				status="2";
            				message="调用第三方推送接口异常";
            			}
            			/**
            			 * 推送失败，并且推送次数小于3次,需要更新下次执行时间
            			 */
            			IfControlCheckConclusionPushBean bean=new IfControlCheckConclusionPushBean();
            			if("2".equals(status)&&count<2){
            				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            				Date now = new Date();
            				Date nowAdd = new Date(now.getTime()+1*60*1000);
            				String plan_pushtime=format.format(nowAdd); 
            				bean.setPlan_pushtime(plan_pushtime);
            			}
            			bean.setMessage(message);
            			bean.setPush_count(count+1);
            			bean.setStatus(status);
            			bean.setId(id);
            			dataOperator.updateInfoControlPushInfo(bean);//更新推送状态等信息
            		}
            	}catch(Exception err){
            		log.error("推送信控核查结论失败", err);
            	}
			}
		}
		
		/**
		 * 推送语音通知核查结果
		 * @param url 推送地址
		 * @param data 推送数据
		 * @return
		 */
		private String pushCheckInfo(String url,String data){
			String response=null;
			if(url.startsWith("https")){
				//推送地址为https
				HttpClientCenter httpClientCenter = new HttpClientCenter(url);
				response = httpClientCenter.postHttps(data, "application/json");
			}else if(url.startsWith("http")){
				//推送地址为http
				response = HttpRequest.postData(url, data);
			}else{
				response=INVALID_URL;
			} 
			return response;
		}

	}
	
	
}
